package cn.daniel.goods.service.impl;

import cn.daniel.goods.entity.GoodsImage;
import cn.daniel.goods.mapper.GoodsImageMapper;
import cn.daniel.goods.service.GoodsImageService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Daniel_li
 * @since 2020-12-29
 */
@Service
public class GoodsImageServiceImpl extends ServiceImpl<GoodsImageMapper, GoodsImage> implements GoodsImageService {

    @Override
    public boolean addOrUpDateGoodsImage(List<GoodsImage> goodsImageList) {
        if (goodsImageList.size()>0){
            String goodsId= goodsImageList.get(0).getGoodsId();
            //更新或添加目前前端修改相册的请求
            for (GoodsImage goodsImage : goodsImageList) {
                if (goodsImage.getImageId().isEmpty()){
                    baseMapper.insert(goodsImage);
                }else {
                    baseMapper.updateById(goodsImage);
                }
            }
            //接着删除旧的图片
            QueryWrapper<GoodsImage> wrapper = new QueryWrapper<>();
            wrapper.eq("goods_id",goodsId);
            wrapper.isNull("comment_id");
            List<GoodsImage> list = baseMapper.selectList(wrapper);
            //图片如果大于前端传递过来的goodsImageList中的图片数量 就删除旧的，只保留最新goodsImageList
            if (list.size()>goodsImageList.size()){
                for (GoodsImage image : list) {
                    //判定是否为旧的图片
                    boolean isdelete=true;
                    for (GoodsImage goodsImage : goodsImageList) {
                        //如果goodsImage的imageSource值在最新的goodsImageList中存在，即不删除
                        if (image.getImageSource()==goodsImage.getImageSource()){
                            isdelete=false;
                            break;
                        }
                    }
                    //根据isdelete的值是否决定删除
                    if (isdelete){
                        baseMapper.deleteById(image.getImageId());
                    }
                }
            }
            return true;
        }
        return false;
    }
}
